<?php
defined('BASEPATH') or exit('No direct script access allowed');

class Login extends CI_Controller
{

    public function __construct()
    {
        parent::__construct();

        $this->load->library('layout', array('main')); //加载layouts下的main文件，可以写其他的布局文件，如$this->load->library('layout',array('hello'));表示加载layouts下的hello布局文件，默认$this->load->library('layout')不传参表示加载默认的布局文件，在layout扩展类的构造方法中已经设置了默认参数main
        $this->load->model('Users_model','users');
    }



    public function valiedImg()
    {
        $this->load->helper('captcha');
        $vals = array(
            'img_path'  => './captcha/',
            'img_url'   => 'http://www.cidemo.com/captcha/'
        );

        $cap = create_captcha($vals);



        $data = array(
            'captcha_time'  => $cap['time'],
            'ip_address'    => $this->input->ip_address(),
            'word'      => $cap['word']
        );

        $query = $this->db->insert_string('captcha', $data);
        $this->db->query($query);


        $this->load->view('captcha',['cap'=>$cap]);

        // echo 'Submit the word you see below:';
        // echo $cap['image'];
        // echo '<input type="text" name="captcha" value="" />';
    }

    /**
     * 验证码登录
     * 
     */
    public function valiedImgSave()
    {
        $expiration = time() - 7200; // Two hour limit
        $this->db->where('captcha_time < ', $expiration)
            ->delete('captcha');

        // Then see if a captcha exists:
        $sql = 'SELECT COUNT(*) AS count FROM captcha WHERE word = ? AND ip_address = ? AND captcha_time > ?';
        $binds = array($_POST['captcha'], $this->input->ip_address(), $expiration);
        $query = $this->db->query($sql, $binds);
        $row = $query->row();

        if ($row->count == 0)
        {
            echo 'You must submit the word that appears in the image.';
        }else
        {
            echo 'ok';
        }
    }

    public function index()
    {
        $this->load->view('login');
    }
    /**
     * 用户登录验证
     * f y j
     **/
    public function login()
    {

        if ($_POST) {
            
            $email = trim($this->input->post('email'));
            $password = trim($this->input->post('password'));

            $user = $this->users->find_user($email,$password);

            if ($user) {
                $this->session->set_userdata("user", $user->email);

                redirect('user/index');
            }
            $this->load->view('login');
        }
    }
}
